//----------------------------------Include-------------------------------------
#include "mcu.h"
#include "glbvar.h"
//------------------------------------------------------------------------------

//APB1 : TIM2-7, TIM12-14, LPTIM1
//APB2 : TIM1, TIM8, TIM15-17
//APB4 : LPTIM2-5

//-----------------------------------Macro--------------------------------------
#define _TIM          TIM7
#define _IRQn         TIM7_IRQn
//------------------------------------------------------------------------------

//--------------------------------Static Var------------------------------------
static uint32_t    src_clk;
static uint32_t    clk_div;
static uint32_t    req_freqHz;
static uint32_t    period_cnt;
//------------------------------------------------------------------------------

//--------------------------------Public Func-----------------------------------
void mcu_delay_ms(uint32_t ms)
{
  uint64_t  t;
  t = igu64_tick_ms;
  while( t + ms > igu64_tick_ms );
}
//------------------------------------------------------------------------------
void mcu_init_tim7(void)
{
//periph clock
  __HAL_RCC_TIM7_CLK_ENABLE();
  
//timer base
  src_clk    = mcu_get_pclk1() *2;
  clk_div    = 1000;
  req_freqHz = 1000;       //Hz
  period_cnt = (src_clk/clk_div)/req_freqHz;
  
  LL_TIM_InitTypeDef    TIM_InitS;
  LL_TIM_StructInit   (&TIM_InitS);
  TIM_InitS.Prescaler         = clk_div -1;
  TIM_InitS.CounterMode       = LL_TIM_COUNTERMODE_UP;
  TIM_InitS.Autoreload        = period_cnt -1;
  TIM_InitS.ClockDivision     = LL_TIM_CLOCKDIVISION_DIV1;
  TIM_InitS.RepetitionCounter = 0;
  LL_TIM_Init(_TIM, &TIM_InitS);
  
//interrupt
  LL_TIM_EnableIT_UPDATE(_TIM);
  
  HAL_NVIC_SetPriority(_IRQn, 3, 3);
  HAL_NVIC_EnableIRQ(_IRQn);
  
//enable
  LL_TIM_EnableCounter(_TIM);
}
//------------------------------------ISR---------------------------------------
void TIM7_IRQHandler(void)
{
  if(_TIM->SR &  (1<<0)){
    _TIM->SR &= ~(1<<0);
    
    igu64_tick_ms++;
    
    static unsigned int cnt;
    if(++cnt >= 2000){
      cnt = 0;
      //mcu_led_toggle();
    }
  }
  
  if(_TIM->SR){
    _TIM->SR = 0;
  }
}
//------------------------------------EOF---------------------------------------




